package com.renjun.smweb.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.renjun.smweb.commons.componet.BaseDaoComponent;
import com.renjun.smweb.commons.global.DataMap;
import com.renjun.smweb.commons.global.StaticCaches;
import com.renjun.smweb.dao.bean.InsertParams;
import com.renjun.smweb.dao.pojo.LoginInfo;
import com.renjun.smweb.commons.componet.BaseDaoComponent;
import com.renjun.smweb.commons.global.DataMap;
import com.renjun.smweb.dao.bean.InsertParams;
import com.renjun.smweb.dao.pojo.LoginInfo;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class SessionInterceptor extends HandlerInterceptorAdapter  {

	@Resource
	private BaseDaoComponent baseDaoComponent;
//	@Autowired
//	private IAuthorityService authorityService;

	public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排除
	
	public void setAllowUrls(String[] allowUrls) {  
        this.allowUrls = allowUrls;  
    } 
	
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterConcurrentHandlingStarted(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		if(StaticCaches.getRealRootPath()==null) {
			StaticCaches.setRealRootPath(request.getServletContext().getRealPath("/"));//设置根目录
		}
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");

//		if("/webinfo/getWebinfo".equals(requestUrl)){
//			return  true;
//		}
		if(null != allowUrls && allowUrls.length>=1)
            for(String url : allowUrls) {
                if(requestUrl.contains(url)) {
                    return true;
                }
            }


		HttpSession session =  request.getSession();
		String ip = request.getHeader("x-forwarded-for");
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
			ip = request.getRemoteAddr();
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = sdf.format(new Date());
		Map<String,Object> map = new DataMap<>();
		map.put("loginip",ip);
		map.put("lastlogintime",time);
		InsertParams insertParams = InsertParams.createInsertParams("T_LOGIN_LOG");
		insertParams.addParamsForMap(map);
		if (null!=session) {
			LoginInfo adminInfo = (LoginInfo) session.getAttribute("userinfo");
			//升级改造，接口是否可用
			List<Map<String, Object>> funcList = StaticCaches.getFunctionsByRoleId(adminInfo.getRoleid());
			if (null!=funcList) {
				for(Map<String,Object> func : funcList) {
					String funcUrl = (String) func.get("url");
					if(null!=funcUrl) {
						if(requestUrl.contains(funcUrl)) {
							//取值 status 0为可用1为不可用
							String status = (String) func.get("status");
							if("1".equals(status)) {
								JSONObject noSession = new JSONObject();
								noSession.put("status","nointerface");
								noSession.put("message","接口已经被禁用，具体原因，请联系管理员。");
								response.setCharacterEncoding("UTF-8");
								PrintWriter pw = response.getWriter();
								pw.write(noSession.toJSONString());
								pw.flush();
								pw.close();
//								request.getRequestDispatcher("/dist/public/error.html").forward(request, response);
								return false;
							}
						}
					}
				}
			}

			if(adminInfo!=null) {
				Map<String,Object> map1 = new DataMap<>();
				map1.put("LOGENAME", adminInfo.getRealname());
				insertParams.addParamsForMap(map1);
				//				baseDaoComponent.insertDataByParams(insertParams);
				return true;
			}
		}

        JSONObject noSession = new JSONObject();
        noSession.put("status","nosession");
        PrintWriter pw = response.getWriter();
        pw.write(noSession.toJSONString());
        pw.flush();
        pw.close();
//}
//		baseDaoComponent.insertDataByParams(insertParams);
		request.getRequestDispatcher("/dist/public/login.html").forward(request, response);
		return false;
	}

	

}
